package com.hwxm.ltim.config;

import com.hwxm.ltim.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT 拦截器
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 跳过不需要验证的路径
        if (isSkipPath(requestURI)) {
            return true;
        }

        // 获取 Authorization 头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未提供有效的认证信息\"}");
            return false;
        }

        // 提取 token
        String token = authHeader.substring(7);
        
        // 验证 token
        if (!jwtUtil.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"认证信息无效或已过期\"}");
            return false;
        }

        // 将用户ID存储到请求属性中，供后续使用
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId != null) {
            request.setAttribute("userId", userId);
        }

        return true;
    }

    /**
     * 判断是否跳过验证的路径
     */
    private boolean isSkipPath(String requestURI) {
        // 跳过注册、登录和密码重置相关接口
        return requestURI.contains("/api/auth/register") ||
               requestURI.contains("/api/auth/login") ||
               requestURI.contains("/api/auth/send-verification-code") ||
               requestURI.contains("/api/auth/verify-code") ||
               requestURI.contains("/api/auth/email-register") ||
               requestURI.contains("/api/auth/reset-password") ||
               requestURI.startsWith("/app/images/"); // 跳过静态图片资源访问
    }
}
